import {/*observable, */action, toJS} from 'mobx';
export default class RichTextStore {
  editor;
  focusManager = null;
  callBackList = [];
  isInited = false;
  
  constructor(params) {
    if (params) {
      this.callBackList.push(params.initEndCallback);
    }
  }
  
  @action
  // ckEditor -- 插入 html
  insertHtml(html) {
    if (this.editor) {
      this.focusManager.lock();
      // if (typeof(this.getText()) === 'undefined') {
      //   this.setText("");// 报过一个奇怪的undefined报错,猜测是这里的问题,加个判断处理下
      // }
      this.editor.insertHtml(html, 'html', null, false);
      this.focusManager.unlock();
      // this.focusManager.blur();
    } else {
      this.callBackList.push(() => {
        this.insertHtml(html);
      });
    }
  }
  
  setData = (v) => {
    if (this.editor) {
      this.editor.setData(v);
    } else {
      this.callBackList.push(() => {
        this.setData(v);
      });
    }
  }
  
  getData = () => {
    return this.editor.getData();
  }
  
  clear = () => {
    this.editor && this.editor.setData('');
  }
  
  // ckEditor -- 初始化
  createEditor = (id, props) => {
    const config = { // 富文本配置
      toolbar:[
         { name: 'document', items: [ 'Source'] },
         { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
         { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
         { name: 'colors', items: [ 'TextColor' ] },
         { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] },
         { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
      ],
      toolbarCanCollapse: true,
      toolbarStartupExpanded: false,
      uploadUrl: '/api/doc/upload/uploadFile',
      // extraPlugins: 'markdown',
      resize_enabled: false,
      allowedContent: true,
      removePlugins: "toolbar",
      startupFocus: true,//不开这个，直接点表情时会报undefined.
      ...props.config
    };
  
    // this.editor = window.CKEDITOR.replace(id, config);
    let dom = document.getElementById(id);
    dom.setAttribute('contenteditable', true);

    this.editor = window.CKEDITOR.inline(id, config);
    this.focusManager = new window.CKEDITOR.focusManager(this.editor);
    
    const {onChange, text} = props;
    text && this.editor.setData(text);
    onChange && this.editor.on('change', e => { // 监听onChange事件
      onChange(e.editor.getData());
    });
    
    this.isInited = true;
    this.initCallBack();
  }
  initCallBack = () => {
    let list = toJS(this.callBackList);
    this.callBackList = [];
    if (list.length === 0) {
      return;
    }
    list.forEach((func) => {
      if (typeof(func) === 'function') {
        func();
      }
    })
    this.initCallBack();//避免callBackList中有新值的情况。
  }
}